<!-- 文件名: app/templates/videos.html -->
{% extends "base.html" %}

{% block title %}视频列表 - 社交媒体监控{% endblock %}

{% block page_title %}视频列表{% endblock %}

{% block content %}
{% if username %}
<h3>{{ username }} 的视频</h3>
<p><a href="/users/{{ user_id }}" class="btn btn-sm btn-secondary mb-3">返回用户详情</a></p>
{% endif %}

<!-- 搜索和筛选 -->
<div class="card mb-3">
    <div class="card-body">
        <form method="get" action="/videos" class="row g-3">
            {% if user_id %}
            <input type="hidden" name="user_id" value="{{ user_id }}">
            {% endif %}
            <div class="col-md-4">
                <label for="search" class="form-label">搜索描述</label>
                <input type="text" class="form-control" id="search" name="search" value="{{ search or '' }}">
            </div>
            <div class="col-md-2">
                <label for="platform" class="form-label">平台</label>
                <select class="form-select" id="platform" name="platform">
                    <option value="">全部平台</option>
                    <option value="tiktok" {% if platform==
                    'tiktok' %}selected{% endif %}>TikTok</option>
                    <option value="douyin" {% if platform==
                    'douyin' %}selected{% endif %}>抖音</option>
                    <option value="instagram" {% if platform==
                    'instagram' %}selected{% endif %}>Instagram</option>
                    <option value="kuaishou" {% if platform==
                    'kuaishou' %}selected{% endif %}>快手</option>
                </select>
            </div>
            <div class="col-md-2">
                <label for="status" class="form-label">状态</label>
                <select class="form-select" id="status" name="status">
                    <option value="">全部状态</option>
                    <option value="downloaded" {% if status==
                    'downloaded' %}selected{% endif %}>已下载</option>
                    <option value="pending" {% if status==
                    'pending' %}selected{% endif %}>下载中</option>
                    <option value="failed" {% if status==
                    'failed' %}selected{% endif %}>下载失败</option>
                </select>
            </div>
            <div class="col-md-2">
                <label for="per_page" class="form-label">每页显示</label>
                <select class="form-select" id="per_page" name="per_page">
                    <option value="10" {% if pagination.per_page== 10 %}selected{% endif %}>10</option>
                    <option value="20" {% if pagination.per_page== 20 %}selected{% endif %}>20</option>
                    <option value="50" {% if pagination.per_page== 50 %}selected{% endif %}>50</option>
                </select>
            </div>
            <!-- 时间范围选择 -->
            <div class="d-flex">
                <div>
                    <label for="startDate">开始时间:</label>
                    <input type="date" id="startDate" class="form-control" name="start_date" value="{{ start_date or '' }}">
                </div>
                <div style="margin-left: 8px">
                    <label for="endDate">结束时间:</label>
                    <input type="date" id="endDate" class="form-control" name="end_date" value="{{ end_date or '' }}">
                </div>
                <!-- 下载视频总数 -->
                <div style="margin-left: 8px" {% if not start_date or not end_date %} hidden {% endif %}>
                    <label for="downloadTotalCount">下载总数：</label>
                    <input disabled type="number" id="downloadTotalCount" class="form-control" value="{{ total_download_count }}">
                </div>

            </div>

            <div class="col-md-2 d-flex align-items-end">
                <button type="submit" class="btn btn-primary me-2">搜索</button>
                <a href="/videos{% if user_id %}?user_id={{ user_id }}{% endif %}" class="btn btn-secondary">重置</a>
            </div>
        </form>
    </div>
</div>

<div class="mb-3">
    <button id="batchDeleteBtn" class="btn btn-danger" style="display: none;" onclick="batchDelete()">批量删除</button>
</div>

<div class="table-responsive">
    <table class="table table-striped">
        <thead>
        <tr>
            <th><input type="checkbox" id="selectAll" onclick="toggleSelectAll()"></th>
            <th>平台</th>
            <th>用户</th>
            <th>描述</th>
            <th>状态</th>
            <th>下载时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        {% for video in videos %}
        <tr>
            <td><input type="checkbox" class="video-checkbox" value="{{ video.id }}"
                       onchange="updateBatchDeleteButton()"></td>
            <td>
                <span class="badge platform-{{ video.platform }}">{{ video.platform }}</span>
            </td>
            <td>{{ video.username }}</td>
            <td>{{ video.title }}</td>
            <td>
                {% if video.download_status == "downloaded" %}
                <span class="badge bg-success">已下载</span>
                {% elif video.download_status == "pending" %}
                <span class="badge bg-warning">下载中</span>
                {% else %}
                <span class="badge bg-danger">下载失败</span>
                {% endif %}
            </td>
            <td>{{ video.download_at }}</td>
            <td>
                {% if video.download_status == "downloaded" %}
                <a href="/play/{{ video.id }}" class="btn btn-sm btn-primary">播放</a>
                {% elif video.download_status == "failed" and video.last_download_url %}
                <a href="{{ video.last_download_url }}" target="_blank" class="btn btn-sm btn-warning">
                    <i class="bi bi-download"></i> 手动下载
                </a>
                {% endif %}
                <a href="/users/{{ video.user_id }}" class="btn btn-sm btn-info">用户详情</a>
                <a href="#" class="btn btn-sm btn-danger"
                   onclick="deleteVideo({{ video.id }}, '{{ video.title|truncate(20) }}'); return false;">删除</a>
            </td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
</div>

{% if videos|length == 0 %}
<div class="alert alert-info">
    没有视频数据
</div>
{% endif %}

<!-- 分页导航 -->
{% if pagination.pages > 1 %}
<nav aria-label="Page navigation">
    <ul class="pagination justify-content-center">
        <li class="page-item {% if pagination.page == 1 %}disabled{% endif %}">
            <a class="page-link"
               href="?page=1&per_page={{ pagination.per_page }}{% if user_id %}&user_id={{ user_id }}{% endif %}{% if platform %}&platform={{ platform }}{% endif %}{% if status %}&status={{ status }}{% endif %}{% if search %}&search={{ search }}{% endif %}"
               aria-label="First">
                <span aria-hidden="true">首页</span>
            </a>
        </li>
        <li class="page-item {% if pagination.page == 1 %}disabled{% endif %}">
            <a class="page-link"
               href="?page={{ pagination.page - 1 }}&per_page={{ pagination.per_page }}{% if user_id %}&user_id={{ user_id }}{% endif %}{% if platform %}&platform={{ platform }}{% endif %}{% if status %}&status={{ status }}{% endif %}{% if search %}&search={{ search }}{% endif %}"
               aria-label="Previous">
                <span aria-hidden="true">上一页</span>
            </a>
        </li>

        {% set start_page = (pagination.page - 2) if (pagination.page - 2) > 0 else 1 %}
        {% set end_page = (start_page + 4) if (start_page + 4) <= pagination.pages else pagination.pages %}
        {% if end_page - start_page < 4 and start_page > 1 %}
        {% set start_page = (end_page - 4) if (end_page - 4) > 0 else 1 %}
        {% endif %}

        {% for p in range(start_page, end_page + 1) %}
        <li class="page-item {% if p == pagination.page %}active{% endif %}">
            <a class="page-link"
               href="?page={{ p }}&per_page={{ pagination.per_page }}{% if user_id %}&user_id={{ user_id }}{% endif %}{% if platform %}&platform={{ platform }}{% endif %}{% if status %}&status={{ status }}{% endif %}{% if search %}&search={{ search }}{% endif %}">{{
                p }}</a>
        </li>
        {% endfor %}

        <li class="page-item {% if pagination.page == pagination.pages %}disabled{% endif %}">
            <a class="page-link"
               href="?page={{ pagination.page + 1 }}&per_page={{ pagination.per_page }}{% if user_id %}&user_id={{ user_id }}{% endif %}{% if platform %}&platform={{ platform }}{% endif %}{% if status %}&status={{ status }}{% endif %}{% if search %}&search={{ search }}{% endif %}"
               aria-label="Next">
                <span aria-hidden="true">下一页</span>
            </a>
        </li>
        <li class="page-item {% if pagination.page == pagination.pages %}disabled{% endif %}">
            <a class="page-link"
               href="?page={{ pagination.pages }}&per_page={{ pagination.per_page }}{% if user_id %}&user_id={{ user_id }}{% endif %}{% if platform %}&platform={{ platform }}{% endif %}{% if status %}&status={{ status }}{% endif %}{% if search %}&search={{ search }}{% endif %}"
               aria-label="Last">
                <span aria-hidden="true">末页</span>
            </a>
        </li>
    </ul>
</nav>
<div class="text-center">
    <small class="text-muted">共 {{ pagination.total }} 条记录，当前第 {{ pagination.page }}/{{ pagination.pages }}
        页</small>
</div>
{% endif %}
{% endblock %}

{% block scripts %}
<script>
    function toggleSelectAll() {
        const selectAllCheckbox = document.getElementById('selectAll');
        const videoCheckboxes = document.getElementsByClassName('video-checkbox');

        for (let checkbox of videoCheckboxes) {
            checkbox.checked = selectAllCheckbox.checked;
        }

        updateBatchDeleteButton();
    }

    function updateBatchDeleteButton() {
        const videoCheckboxes = document.getElementsByClassName('video-checkbox');
        const batchDeleteBtn = document.getElementById('batchDeleteBtn');

        let checkedCount = 0;
        for (let checkbox of videoCheckboxes) {
            if (checkbox.checked) {
                checkedCount++;
            }
        }

        batchDeleteBtn.style.display = checkedCount > 0 ? 'inline-block' : 'none';
        batchDeleteBtn.textContent = `批量删除 (${checkedCount})`;
    }

    function batchDelete() {
        const videoCheckboxes = document.getElementsByClassName('video-checkbox');
        const selectedIds = [];

        for (let checkbox of videoCheckboxes) {
            if (checkbox.checked) {
                selectedIds.push(parseInt(checkbox.value));
            }
        }

        if (selectedIds.length === 0) {
            return;
        }

        if (confirm(`确定要删除选中的 ${selectedIds.length} 个视频吗？此操作不可恢复。`)) {
            // 使用批量删除API
            fetch('/api/videos-batch', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(selectedIds),
            })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    location.reload();
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('批量删除失败');
                });
        }
    }

    function deleteVideo(videoId, title) {
        if (confirm(`确定要删除视频 "${title}" 吗？此操作不可恢复。`)) {
            fetch(`/api/videos/${videoId}`, {
                method: 'DELETE',
            })
                .then(response => {
                    if (response.ok) {
                        alert('视频删除成功');
                        location.reload();
                    } else {
                        alert('删除失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败');
                });
        }
    }

    // 根据日期筛选
    function filterByDate() {
        const startDate = document.getElementById('startDate').value;
        const endDate = document.getElementById('endDate').value;

        let url = `/videos?start_date=${startDate}&end_date=${endDate}`;

        fetch(url)
            .then(response => response.json())
            .then(data => {
                // 更新表格数据
                updateTable(data.items);
                document.getElementById('downloadTotalCount').innerText = `下载总数：${data.total}`;
            });
    }

    function updateTable(videos) {
        const tbody = document.querySelector('tbody');
        tbody.innerHTML = '';  // 清空现有内容

        videos.forEach(video => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td><input type="checkbox" class="video-checkbox" value="${video.id}" onchange="updateBatchDeleteButton()"></td>
                <td><span class="badge platform-${video.platform}">${video.platform}</span></td>
                <td>${video.username}</td>
                <td>${video.title}</td>
                <td>${video.download_status === 'downloaded' ? '<span class="badge bg-success">已下载</span>' :
                    video.download_status === 'pending' ? '<span class="badge bg-warning">下载中</span>' :
                    '<span class="badge bg-danger">下载失败</span>'}</td>
                <td>${video.download_at}</td>
                <td>
                    ${video.download_status === 'downloaded' ? `<a href="/play/${video.id}" class="btn btn-sm btn-primary">播放</a>` : ''}
                    ${video.download_status === 'failed' && video.last_download_url ? `<a href="${video.last_download_url}" target="_blank" class="btn btn-sm btn-warning"><i class="bi bi-download"></i> 手动下载</a>` : ''}
                    <a href="/users/${video.user_id}" class="btn btn-sm btn-info">用户详情</a>
                    <a href="#" class="btn btn-sm btn-danger" onclick="deleteVideo(${video.id}, '${video.title|truncate(20)}'); return false;">删除</a>
                </td>
            `;
            tbody.appendChild(row);
        });
    }
</script>
{% endblock %}